<template>
  <div style="display: flex">
    <!-- 选择机构 -->

    <div style="margin-top: 1%; margin-left: 3%">
      <el-select
        v-model="mechanismName"
        placeholder="请选择机构"
        @change="mechanismchange"
      >
        <el-option
          v-for="item in mechanismList"
          :key="item.id"
          :label="item.mec_name"
          :value="item.id"
        />
      </el-select>
    </div>
    <el-dropdown
      v-if="getUserList"
      @command="handleCommand"
      @visible-change="handleVisibleChange"
    >
      <span class="avatar-dropdown">
        <el-avatar class="user-avatar" :src="getUserList.avatar || src" />
        <div class="user-name">
          <span class="hidden-xs-only">
            {{ getUserList.real_name || getUserList.username }}
          </span>
          <vab-icon
            class="vab-dropdown"
            :class="{ 'vab-dropdown-active': active }"
            icon="arrow-down-s-line"
          />
        </div>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="set_pwd">
            <vab-icon icon="logout-circle-r-line" />
            修改密码
          </el-dropdown-item>
          <el-dropdown-item command="logout">
            <vab-icon icon="logout-circle-r-line" />
            {{ translateTitle('退出登录') }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <el-dialog
      append-to-body
      title="修改密码"
      :visible.sync="dialogVisible"
      width="70%"
    >
      <div>
        <div class="register-container">
          <el-form
            ref="registerForm"
            class="register-form"
            :model="form"
            :rules="registerRules"
            size="mini"
          >
            <div class="title-tips">{{ translateTitle('修改密码') }}</div>

            <el-form-item prop="auth_tel">
              <el-input
                v-model.trim="form.auth_tel"
                maxlength="11"
                :placeholder="translateTitle('请输入手机号')"
                show-word-limit
                type="text"
              />
            </el-form-item>
            <el-form-item prop="sms_code" style="position: relative">
              <el-input
                v-model.trim="form.sms_code"
                :placeholder="translateTitle('请输入手机验证码')"
                type="text"
              />
              <el-button
                class="auth_tel-code"
                :disabled="isGetPhone"
                type="primary"
                @click="getPhoneCode"
              >
                {{ sms_code }}
              </el-button>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model.trim="form.password"
                autocomplete="new-password"
                :placeholder="translateTitle('请输入密码')"
                type="password"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                class="register-btn"
                type="primary"
                @click.native.prevent="handleRegister"
              >
                {{ translateTitle('修改密码') }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { translateTitle } from '@/utils/i18n'
  import { mapActions, mapGetters } from 'vuex'
  import { toLoginRoute } from '@/utils/routes'
  import { getMechanismList, setMec } from '@/api/mechanism'
  import store from '@/store'
  import { authentication } from '@/config'
  import { getUser } from '@/api/router'
  import srcs from '../../../assets/public/default.jpg'

  //

  import { isPassword, isPhone } from '@/utils/validate'
  import { getCode, setPwd } from '@/api/user'

  // register
  //import { getUser } from '@/api/router'

  export default {
    name: 'VabAvatar',
    directives: {
      focus: {
        inserted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          callback(new Error(this.translateTitle('密码不能少于6位')))
        } else {
          callback()
        }
      }
      const validatePhone = (rule, value, callback) => {
        if (!isPhone(value)) {
          callback(new Error(this.translateTitle('请输入正确的手机号')))
        } else {
          callback()
        }
      }
      return {
        active: false,
        mechanismList: [],
        mechanismName: '',
        userInfo: {},
        dialogVisible: false,
        getUserList: {},
        src: srcs,
        isGetPhone: false,
        getPhoneInterval: null,
        sms_code: this.translateTitle('获取验证码'),
        showRegister: false,
        form: {
          auth_tel: '',
          sms_code: '',
          password: '',
        },
        registerRules: {
          // username: [
          //   {
          //     required: true,
          //     trigger: 'blur',
          //     message: this.translateTitle('请输入用户名'),
          //   },
          //   { validator: validateUsername, trigger: 'blur' },
          // ],
          auth_tel: [
            {
              required: true,
              trigger: 'blur',
              message: this.translateTitle('请输入手机号'),
            },
            { validator: validatePhone, trigger: 'blur' },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              message: this.translateTitle('请输入密码'),
            },
            { validator: validatePassword, trigger: 'blur' },
          ],
          sms_code: [
            {
              required: true,
              trigger: 'blur',
              message: this.translateTitle('请输入手机验证码'),
            },
          ],
        },
        loading: false,
        passwordType: 'password',
      }
    },

    computed: {
      ...mapGetters({
        avatar: 'user/avatar',
        real_name: 'user/real_name',
        username: 'user/username',
      }),
      /* userInfo() {
        getUser().then((e) => {
          return e.data
        })
      }, */
    },
    beforeDestroy() {
      this.getPhoneInterval = null
      clearInterval(this.getPhoneInterval)
    },
    created() {
      this.Mechanism()
      this.mechanismName = window.localStorage.getItem('mec_name')
    },
    methods: {
      // 获取机构
      Mechanism() {
        getMechanismList().then((res) => {
          if (res != undefined) {
            this.mechanismList = res.data.list
          }
        })
        getUser().then((e) => {
          this.getUserList = e.data
        })
      },
      mechanismchange(e) {
        this.mechanismList.forEach((j) => {
          if (j.id == e) {
            window.localStorage.setItem(
              'work_week',
              JSON.stringify(j.work_week)
            )
            window.localStorage.setItem(
              'afternoon_end_time',
              j.afternoon_end_time
            )
            window.localStorage.setItem(
              'morning_start_time',
              j.morning_start_time
            )
            window.localStorage.setItem(
              'afternoon_start_time',
              j.afternoon_start_time
            )

            window.localStorage.setItem('morning_end_time', j.morning_end_time)
            window.localStorage.setItem('mec_type', j.mec_type)
            window.localStorage.setItem('mec_name', j.mec_name)
            window.localStorage.setItem('mec_id', e)
          }
        })

        this.mechanismList.forEach((k) => {
          if (k.id == e) {
            //

            setMec(k.mec_code).then(async (res) => {
              try {
                window.localStorage.setItem(
                  'lang',
                  JSON.stringify(res.data.lang)
                )
                await store.dispatch('routes/setRoutes', authentication)
                await this.$router.push('/')
                history.go(0)
              } finally {
                // console.log('123')
              }
            })
          }
        })
      },
      translateTitle,
      ...mapActions({
        _logout: 'user/logout',
      }),
      handleCommand(command) {
        switch (command) {
          case 'logout':
            this.logout()
            break
          case 'set_pwd':
            this.isGetPhone = false
            this.form.auth_tel = ''
            this.form.sms_code = ''
            this.form.password = ''
            this.dialogVisible = true
            break
        }
      },
      handleVisibleChange(val) {
        this.active = val
      },
      async logout() {
        await this._logout()
        await this.$router.push(toLoginRoute(this.$route.fullPath))
      },

      ...mapActions({
        setToken: 'user/setToken',
      }),
      getPhoneCode() {
        if (!isPhone(this.form.auth_tel)) {
          this.$refs['registerForm'].validateField('auth_tel')
          return
        }
        const data = {
          auth_tel: this.form.auth_tel,
          type: 'set_pwd',
        }

        getCode(data).then(() => {
          this.isGetPhone = true
          let n = 60
          this.getPhoneInterval = setInterval(() => {
            if (n > 0) {
              n--
              this.sms_code = this.translateTitle('获取验证码 ') + n + 's'
            } else {
              clearInterval(this.getPhoneInterval)
              this.sms_code = this.translateTitle('获取验证码')
              this.getPhoneInterval = null
              this.isGetPhone = false
            }
          }, 1000)
        })
      },
      handleRegister() {
        this.$refs['registerForm'].validate(async (valid) => {
          if (valid) {
            setPwd(this.form).then(() => {
              this.isGetPhone = false
              this.form.auth_tel = ''
              this.form.sms_code = ''
              this.form.password = ''
              this.dialogVisible = false
            })
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .avatar-dropdown {
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: center;
    justify-items: center;

    .user-avatar {
      width: 40px;
      height: 40px;
      margin-left: 15px;
      cursor: pointer;
      border-radius: 50%;
    }

    .user-name {
      min-width: 80px;
      position: relative;
      display: flex;
      align-content: center;
      align-items: center;
      height: 40px;
      margin-left: 6px;
      line-height: 40px;
      cursor: pointer;

      [class*='ri-'] {
        margin-left: 0 !important;
      }
    }
  }
  .register-container {
    .register-form {
      border-radius: 6%;
      position: relative;
      max-width: 100%;
      padding: 3.5vh;
      margin: calc((100vh - 590px) / 2) 5vw 5vw;
      overflow: hidden;
      background: #fff;
      background-size: 100% 100%;
      position: relative;

      .img {
        width: 100px;
        height: 100px;
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
      }

      .title-tips {
        margin-top: 29px;
        font-size: 26px;
        font-weight: 400;
        // color: $base-color-white;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .register-btn {
        display: inherit;
        width: 220px;
        height: 30px;
        margin-top: 5px;
        border: 0;

        &:hover {
          opacity: 0.9;
        }
      }

      .auth_tel-code {
        position: absolute;
        top: 8px;
        right: 10px;
        width: 120px;
        height: 32px;
        font-size: 14px;
        color: #fff;
        cursor: pointer;
        user-select: none;
        border-radius: 3px;
      }
    }
    .router-to {
      width: 100px;
      float: left;
    }
    .tips {
      margin-bottom: 10px;
      font-size: $base-font-size-default;
      color: $base-color-white;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    ::v-deep {
      .el-form-item {
        padding-right: 0;
        margin: 20px 0;
        color: #454545;
        background: transparent;
        border: 1px solid transparent;
        border-radius: 2px;

        i {
          position: absolute;
          top: 8px;
          left: 5px;
          z-index: $base-z-index;
          font-size: 16px;
          color: #d7dee3;
          cursor: pointer;
          user-select: none;
        }

        &__content {
          min-height: $base-input-height;
          line-height: $base-input-height;
        }

        &__error {
          position: absolute;
          top: 100%;
          left: 18px;
          font-size: $base-font-size-small;
          line-height: 18px;
          color: $base-color-red;
        }
      }

      .el-input {
        box-sizing: border-box;

        input {
          height: 48px;
          padding-left: 35px;
          font-size: $base-font-size-default;
          line-height: 58px;
          background: #f6f4fc;
          border: 0;
        }
      }
    }
  }
  .vab-footer {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 55px;
    padding: 0 $base-padding 0 $base-padding;
    color: rgba(0, 0, 0, 0.45);
    background: $base-color-white;
    border-top: 1px dashed $base-border-color;

    i {
      margin: 0 5px;
    }
  }
</style>
